package com.geline.mybatisplus.util;

import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.geline.mybatisplus.annotation.TableFieldBsm;
import com.geline.mybatisplus.handler.EntityFieldHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cglib.beans.BeanMap;

import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author: mengxin
 * @date: 2023/12/4 10:51
 */
@Slf4j
public class TableFieldBsmUtil {

    public static boolean handle(Object entity){
        //处理Field上的 @TableFieldBsm
        boolean change = false;
        List<Field> fieldList = getFieldList(entity);
        log.debug("find @TableFieldBsm = {}", fieldList.size());
        if(fieldList!=null && fieldList.size()>0){
            for (Field field : fieldList) {
                Object fieldValue = BeanMap.create(entity).get(field.getName());
                //只有标识码为null时才设置值
                if(StrUtil.isBlankIfStr(fieldValue)){
                    TableFieldBsm annotation = field.getAnnotation(TableFieldBsm.class);
                    EntityFieldHandler handler = SpringUtil.getBean(annotation.handler());
                    handler.before(entity, field, annotation);
                    //insert前生成新bsm，用新的entity
                    change = true;
                    log.info("success to init @TableFieldBsm[{}={}]", field.getName(), BeanMap.create(entity).get(field.getName()));
                }
            }
        }
        return change;
    }

    private static List<Field> getFieldList(Object entity){
        Field[] declaredFields = entity.getClass().getDeclaredFields();
        List<Field> currentList = Arrays.asList(declaredFields).stream().filter(t -> t.isAnnotationPresent(TableFieldBsm.class)).collect(Collectors.toList());
        return currentList;
    }
}
